package com.example.ruiji.controller;

import com.example.ruiji.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${ruiji.path}")
    private String path;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String[] split = Objects.requireNonNull(originalFilename).split("\\.");
        String suffix = split[split.length - 1];

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String fileName = UUID.randomUUID().toString();
        String fullFileName = fileName + "." + suffix;
        file.transferTo(new File(path + fullFileName));
        return Result.success(fullFileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse httpServletResponse) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(new File(path + name));
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        httpServletResponse.setContentType("image/jpeg");

        int len;
        byte[] bytes = new byte[1024];
        while ( (len = fileInputStream.read(bytes)) != -1 ) {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }
        outputStream.close();
        fileInputStream.close();
    }
}
